<?php
class JVPhoto
{
	private $_cachePath;
	private $_serverCachePath;
	
	private $_path;
	private $_serverPath;
	
	private $_id = null;
	
	public function __construct($id)
	{
		$this->_id = $id;
		
		$this->_cachePath = '/images/cache/';
		$this->_serverCachePath = $_SERVER['DOCUMENT_ROOT'] . $this->_cachePath;

		$this->_path = '/images/photos/'.$id.'.jpg';
		$this->_serverPath = $_SERVER['DOCUMENT_ROOT'] . $this->_path;
	}
	
	public function getPath()
	{
		return $this->_path;
	}
	
	public function getServerPath()
	{
		return $this->_serverPath;
	}
	
	public function toHTML($width, $height, $name = null)
	{
		return '
		<a style="width:'.$width.'px;height:'.$height.'px;" rel="shadowbox[gallery]" href="'.$this->resize(800, 600).'"'.(is_null($name) ? '' : ' title="'.$name.'"').'>
			<img src="'.$this->resize($width, $height).'" />
		</a>';
	}
	
	public function restore($get = null)
	{
		if($this->_id)
		{
			$db = JVMySQL::get();
			$data = $db->getRow('SELECT * FROM PHOTOS WHERE ID = '.$this->_id);
			if($data)
			{
				if(is_null($get))
				{
					return $data;
				}
				else 
				{
					return $data[$get];
				}
			}
		}
		
		return false;
	}
	
	public function resize($width, $height)
	{
		$options["width"] = $width;
		$options["height"] = $height;
		
		if (empty($this->_serverCachePath) || !file_exists($this->_serverPath))
		{
			return false;
		}
		
		$options["width"] = (isset($options["width"]) && is_numeric($options["width"])) ? $options["width"] : 0;
		$options["height"] = (isset($options["height"]) && is_numeric($options["height"])) ? $options["height"] : 0;
		
		// Get file extension to append to cache file
		$fileinfo = pathinfo($this->_serverPath);
		$fileinfo['extension'] = (!isset($fileinfo['extension'])) ? 'png' : strtolower($fileinfo['extension']);
		if (!in_array($fileinfo['extension'], array('png', 'jpg', 'gif')))
		{
			$fileinfo['extension'] = 'png';
		}

		$shortPath = $options['width'] . '_' . $options['height'];
		$outputName = md5($this->_serverPath . filemtime($this->_serverPath)) . '.' . $fileinfo['extension'];
		if (file_exists($this->_serverCachePath . $shortPath . '/' . $outputName))
		{
			return ($this->_cachePath . $shortPath . '/' . $outputName);
		}
		else
		{
			if(!is_dir($this->_serverCachePath.$shortPath))
			{
				mkdir($this->_serverCachePath.$shortPath);
			}
			
			$source = null;
			if(file_exists($this->_serverPath) && is_readable($this->_serverPath) && ($infos = getimagesize($this->_serverPath)))
			{
				$width = $infos[0];
				$height = $infos[1];
				if($this->canAlocateMemory($infos))
				{
					switch($infos[2])
					{
						case IMAGETYPE_JPEG:
							$source = imagecreatefromjpeg($this->_serverPath);
							break;
						case IMAGETYPE_PNG:
							$source = imagecreatefrompng($this->_serverPath);
							break;
						case IMAGETYPE_GIF:
							$source = imagecreatefromgif($this->_serverPath);
							break;
						default:
							$source = null;
					}
				}
				
				if($source != null)
				{
					if(($width <= $options["width"] || $options["width"] == 0) && ($height <= $options["height"] || $options["height"] == 0))
					{
						$output = self::imagecreatetruecolortransparent($source, $infos[2], $width, $height);
						imagecopyresampled($output, $source, 0, 0, 0, 0, $width, $height, $width, $height);
					}
					else
					{
						if($options["width"] != 0)
						{
							$restrictWidth = $width/$options["width"];
						}
						else
						{
							$restrictWidth = 0;
						}
						if($options["height"] != 0)
						{
							$restrictHeight = $height/$options["height"];
						}
						else
						{
							$restrictHeight = 0;
						}
					
					
						if($restrictWidth >= $restrictHeight)
						{ 
							$percent = ($options["width"] / $width) * 100;
							$h = round(($height * $percent) / 100);
							$output = self::imagecreatetruecolortransparent($source, $infos[2], $options["width"], $h)		;
							imagecopyresampled($output, $source, 0, 0, 0, 0, $options["width"], $h, $width, $height); 
						}
						else
						{ 
							$percent = ($options["height"] / $height) * 100;
							$w = round(($width * $percent) / 100);
							$output = self::imagecreatetruecolortransparent($source, $infos[2], $w, $options["height"]);
							imagecopyresampled($output, $source, 0, 0, 0, 0, $w, $options["height"], $width, $height);
						}
					}
					
					// Show image
					switch($infos[2])
					{
						case IMAGETYPE_JPEG:
							// Use it to keep JPG files optimisations
							imagejpeg($output, $this->_serverCachePath.$shortPath . '/' . $outputName);
						break;
						
						case IMAGETYPE_GIF:
							// Use it to keep GIF files optimisations
							imagegif($output, $this->_serverCachePath.$shortPath . '/' . $outputName);
						break;

						default:
							imagepng($output, $this->_serverCachePath.$shortPath . '/' . $outputName);
						break;
					}
					
					return $this->_cachePath . $shortPath."/".$outputName;
				}
			}
			
			if($source == null)
			{
				$outputName = "error.png";
				if(!file_exists($this->_serverCachePath.$shortPath."/".$outputName))
				{
					$output  = self::imagecreatetruecolortransparent(imagecreatetruecolor($options["width"], $options["height"]), IMAGETYPE_PNG, $options["width"], $options["height"]);
					$bgc = imagecolorallocate($output, 255, 255, 255);
					$tc  = imagecolorallocate($output, 0, 0, 0);
					imagefilledrectangle($output, 0, 0, $options["width"], $options["height"], $bgc);
					imagestring($output, 1, 5, 5, "Memory Error", $tc);
					imagepng($output, $this->_serverCachePath.$shortPath."/".$outputName);
				}
				return $this->_cachePath . $shortPath."/".$outputName;
			}
		}
	}
	
	function canAlocateMemory( &$imageInfo )
	{
	    $MB = 1048576;  // number of bytes in 1M
	    $K64 = 65536;    // number of bytes in 64K
	    $TWEAKFACTOR = 1.5;  // Or whatever works for you
	    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
	                                           * $imageInfo['bits']
	                                           * $imageInfo['channels'] / 8
	                             + $K64
	                           ) * $TWEAKFACTOR
	                         );
	    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
	    //Default memory limit is 8MB so well stick with that. 
	    //To find out what yours is, view your php.ini file.
	    $memoryLimit = ini_get('memory_limit') * $MB;
	    
	    if (function_exists('memory_get_usage') && 
	        memory_get_usage() + $memoryNeeded > $memoryLimit) 
	    {
	        return false;
	    }
	    else if(10 * $MB + $memoryNeeded > $memoryLimit)
	    {
	    	//set a random memory limit!!
	    	return false;
	    }
	    
	    return true;
	}
	
	public static function imagecreatetruecolortransparent($image, $type, $x, $y)
	{
		/*
		Old transparent method
		
		$i = imagecreatetruecolor($x,$y);
		$b = imagecreatefromstring(base64_decode("iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADqSURBVHjaYvz//z/DYAYAAcTEMMgBQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAgAEAMpcDTTQWJVEAAAAASUVORK5CYII="));
		imagealphablending($i,false);
		imagesavealpha($i,true);
		imagecopyresized($i,$b,0,0,0,0,$x,$y,imagesx($b),imagesy($b));
		return $i;
		*/
		
		$new = imagecreatetruecolor($x, $y);
		if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG)
		{
			$index = imagecolortransparent($image);
			if ($index >= 0)
			{
				$color = @imagecolorsforindex($image, $index);
				$index = imagecolorallocate($new, $color['red'], $color['green'], $color['blue']);
				imagefill($new, 0, 0, $index);
				imagecolortransparent($new, $index);
			} 
			elseif ($type == IMAGETYPE_PNG)
			{
				imagealphablending($new, false);
				$color = imagecolorallocatealpha($new, 0, 0, 0, 127);
				imagefill($new, 0, 0, $color);
				imagesavealpha($new, true);
			}
		}
    
    	return ($new);

	}
}
?>